# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         module.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/18 17:00
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin, CreateModelMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from apps.HttpAutoTestService.filters import ModuleFilter, ModuleNameFilter
from apps.HttpAutoTestService.models import Module, Api
from apps.HttpAutoTestService.serializers import ModuleListSerializer, ModuleSerializer, ModuleNameListSerializer

__all__ = ['ModuleNameListViewSet', 'ModuleListViewSet', 'ModuleViewSet', 'ModuleMoveAPIView']


class ModuleNameListViewSet(ReadOnlyModelViewSet):
    """
    模块名称列表
    """
    serializer_class = ModuleNameListSerializer
    filter_class = ModuleNameFilter
    pagination_class = None

    def get_queryset(self):
        user = self.request.user
        return Module.objects.filter(
            project__members=user,
            is_deleted=False
        ).order_by('create_time').values('id', 'name', 'parent', 'project', 'is_system', 'floor', 'remark').distinct()


class ModuleListViewSet(ReadOnlyModelViewSet):
    """
    模块列表
    """
    serializer_class = ModuleListSerializer
    filter_class = ModuleFilter

    def get_queryset(self):
        user = self.request.user
        return Module.objects.filter(project__members=user, is_system=False, is_deleted=False).distinct()


class ModuleViewSet(CreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    """
    模块创建、更新
    """
    queryset = Module.objects.filter(is_deleted=False)
    serializer_class = ModuleSerializer

    def create(self, request, *args, **kwargs):
        user = request.user
        data = request.data
        parent = data.get('parent')

        if parent:
            parent_module = Module.objects.filter(id=parent, is_deleted=False).first()
            if parent_module.floor == 4:
                return Response(status=status.HTTP_200_OK, data={'status': 'fail', 'msg': '模块创建失败，原因：模块层级最多为4层'},
                                content_type='application/json')
            else:
                data['floor'] = parent_module.floor + 1
        else:
            data['floor'] = 1
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        module = serializer.save()
        module.creator = user
        module.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        module = Module.objects.get(id=id)
        module.is_deleted = True
        module.save()

        # 获取项目内置模块
        default_module = Module.objects.filter(project_id=module.project_id, is_system=True, is_deleted=False).first()
        Api.objects.filter(module_id=id, is_deleted=False).update(module=default_module)
        return Response(status=status.HTTP_204_NO_CONTENT)


class ModuleMoveAPIView(APIView):
    """
    模块搬家
    """

    def post(self, request, *args, **kwargs):
        data = request.data
        parent = data.get('parent')
        modules = data.get('modules')

        if parent:
            parent_module = Module.objects.get(id=parent)
            parent_module_floor = parent_module.floor
            if parent_module_floor == 4:
                return Response(status=status.HTTP_200_OK, data={'status': 'fail', 'msg': '模块搬家失败，原因：模块层级最多为4层'},
                                content_type='application/json')
            modules_floor = parent_module_floor + 1
            Module.objects.filter(id__in=modules).update(parent=parent, floor=modules_floor)
        return Response(status=status.HTTP_200_OK, data={'status': 'success', 'msg': '模块搬家成功……'},
                        content_type='application/json')
